#include <cstdlib>
#include <cstdio>
#include <ctime>
#include <string>
#include <sstream>
#include <iostream>

#include <SDL.h>
#include <SDL_ttf.h>

#include "tetris_app.h"

using namespace slak::tetris;

struct JaxisSample {
	SDL_Joystick * joy;
	int axis,val;
	Uint32 tm, repeat_delay;

	JaxisSample(SDL_Joystick * joy, int axis, Uint32 repeat_delay) 
		: joy(joy), axis(axis), val(0), repeat_delay(repeat_delay)
	{
		tm = SDL_GetTicks();
	}

	bool sample() 
	{
		int nval = SDL_JoystickGetAxis(joy, axis);
		Uint32 now = SDL_GetTicks();
		std::cerr << (axis?"y":"x") << " = " << nval << "\n";

		if (nval < -8000) 
			nval = -1;
		else if (nval > 8000)
			nval = 1;
		else
			nval = 0;

		if ((nval == val) && ((now-tm)<repeat_delay))
			return false;
		
		tm = now;
		val = nval;
		return true;
	}
};

SDL_Joystick * joy = NULL;

void tetrisShutdown()
{
	if (joy && SDL_JoystickOpened(0)) 
		SDL_JoystickClose(joy);
	SDL_Quit();
}

extern "C" 
int main(int argc,char* argv[])
{
	if (SDL_Init(SDL_INIT_VIDEO|
		     SDL_INIT_TIMER|
		     SDL_INIT_JOYSTICK) < 0) {
		std::cerr << "SDL initialization error: " 
			<< SDL_GetError() << "\n";
		exit(1);
	}
	atexit(tetrisShutdown);

	if (TTF_Init() < 0) {
		std::cerr << "SDL_ttf initialization error: " 
			<< SDL_GetError() << "\n";
		exit(1);
	}

	if(SDL_NumJoysticks()>0){
joy = SDL_JoystickOpen(0);
		std::cout<<"opened joy with " << SDL_JoystickNumAxes(joy) 
			<< " axes and " << SDL_JoystickNumHats(joy) << " hats\n";
		SDL_JoystickEventState(SDL_ENABLE);
	}
#define REPEAT_DELAY 250
	JaxisSample xaxis(joy,0,REPEAT_DELAY), yaxis(joy,1,REPEAT_DELAY);
	SDL_EnableKeyRepeat(REPEAT_DELAY, 
			    50);

	chdir("Tetris.app/Contents/Resources");
	srandom(time(NULL));

	slak::tetris::TetrisApp app(1024, 768);
	app.run();

	exit(0);
}

